<template>
<div class="publishDynamic-wrapper">
  <v-header :handleClick="true" @back="back">
    <p slot="right" @click="publish">发布</p>
  </v-header>
  <scroll ref="scroll" style="overflow: hidden;">
    <div>
      <group>
        <x-textarea v-model="content" :max="200" :rows="4" placeholder="说点什么..." style="margin-top: 0;">
        </x-textarea>

        <grid :cols="3" :show-lr-borders="false" :show-vertical-dividers="false">
          <grid-item  v-for="(img, index) in atlas" :key="index">
            <v-touch class="img-item" v-lazy:backgroundImage="img + '-meitu3'" @tap="clickImg(index)"  @press="press(index)" :press-options="{time: 800}">
            </v-touch>
          </grid-item>
        </grid>
        <cell title="关联产品~" :value="productName" is-link @click.native="linkProduct">
          <img slot="icon" width="24" style="display:block;margin-right:5px;" src="">
        </cell>
      </group>

      <div class="topic">
        <p style="font-size: 17px;">选择的话题</p>
        <div class="content">
          <p class="tag" v-for="(tag, index) in tags" :key="index">#{{tag.name}}#</p>
        </div>
      </div>
    </div>
  </scroll>

  <div v-if="address && address.address" class="address"><i class="fa fa-map-marker" aria-hidden="true" style="margin-right: 5px;"></i>{{address.address}}</div>
  <div class="bottom">
    <input ref="camera" @change="changeFile" type="file" accept="image/*" style="display: none;">
    <div class="icon" @click="toCamera"><i class="fa fa-camera" aria-hidden="true"></i></div>
    <div class="icon" @click="addTag"><i class="fa fa-eyedropper" aria-hidden="true"></i></div>
    <div class="icon" @click="getAddress"><i class="fa fa-map-marker" aria-hidden="true"></i></div>
  </div>

    <!-- 搜索 -->
  <div v-transfer-dom>
    <popup v-model="showSearch" position="right" width="100%"  class="popup-wrapper">
      <div>
        <search-header @submitSearch="submitSearch">
          <p slot="button" @click="showSearch = false">取消</p>
        </search-header>
        <ul class="search-list">
          <li v-for="v in searchList" :key="v.id" @click="clickProductItem(v.id, v.name)">
            <p class="name">{{v.name}}</p>
            <p class="feature">{{v.feature}}</p>
          </li>
        </ul>
        <h4 v-if="searchList.length === 0" style="text-align: center; margin-top: 30%">喔噢~没有数据</h4>
      </div>
    </popup>
  </div>

  <!-- 预览图片 -->
  <div v-transfer-dom>
    <previewer :list="atlasCopy" :options="{loop: false}" @imgLoaded="preImgLoaded" ref="previewer"></previewer>
  </div>
  <router-view />
</div>
</template>

<script>
import headerBg from '@/assets/img/header_bg.png'
import uploadFile from '@/api/uploadFile'
import axios from '@/api/axiosApi'
import { localUser, localTag } from '@/assets/js/local'
import { isIphoneX } from '@/assets/js/brower'

import Scroll from '@/components/scroll/scroll'
import VHeader from '@/components/v-header/v-header'
import SearchHeader from '@/components/seach-header/seach-header'
import Previewer from '@/components/previewer/previewer'
import { Group, XTextarea, Cell, Divider, TransferDom, Popup, Grid, GridItem } from 'vux'
import { mapGetters, mapMutations } from 'vuex'
import { handleBackMixin } from '@/assets/js/mixin'

export default {
  mixins: [handleBackMixin],
  data () {
    return {
      showSearch: false,
      headerBg,
      content: '',
      address: null,
      productId: '',
      productName: '',
      tags: [],
      searchList: [],
      allPopupModels: ['showSearch']
    }
  },
  directives: {
    TransferDom
  },
  components: {
    VHeader, Group, XTextarea, Cell, Divider, Scroll, Popup, SearchHeader, Grid, GridItem, Previewer
  },
  computed: {
    atlasCopy () {
      const tmp = []
      this.atlas.forEach(img => {
        tmp.push({src: img})
      })
      return tmp
    },
    ...mapGetters({
      atlas: 'selectPic'
    })
  },
  mounted () {
    let scrollHeight = window.innerHeight - 40 - 40
    if (isIphoneX()) {
      scrollHeight -= 34
    } else {
      scrollHeight -= 24
    }
    this.$refs.scroll.$el.style.height = scrollHeight + 'px'
  },
  methods: {
    back (success) {
      const _self = this
      if (success) {
        _self.setSelectPic([])
        _self.$router.go(-1)
        return
      }
      this.$vux.confirm.show({
        title: '您正在发布动态，确认要退出吗？',
        content: ' ',
        onConfirm: () => {
          _self.$router.go(-1)
        }
      })
    },
    publish () {
      const userId = localUser.get('id')
      if (userId == null) {
        this.$vux.toast.text('请先登录！', 'middle')
        this.$router.push('/user/login')
        return
      }
      /*
      if (this.content.length === 0) {
        this.$vux.toast.text('请填写动态内容', 'middle')
        return
      }
      */
      if (this.atlas.length === 0) {
        this.$vux.toast.text('请至少选择一张图片发布动态！', 'middle')
        return
      }
      let tagIds = []
      this.tags.forEach(item => {
        tagIds.push(item.id)
      })
      let params = {
        content: this.content,
        atlas: this.atlas.join(';'),
        productId: this.productId,
        publisher: userId,
        tagIds: tagIds.join(';')
      }
      if (this.address) {
        params.publishLongitude = this.address.longitude
        params.publishLatitude = this.address.latitude
        params.publishAddress = this.address.address
      }
      const _self = this
      axios.post(this, '/v1/dynamic', params, (data) => {
        _self.$store.commit('SET_MEITU_TAB', 1)
        _self.$vux.toast.text('发布成功了~', 'middle')
        localTag.push(_self.tags)
        _self.back(true)
      })
    },
    changeFile (e) {
      uploadFile(this, e.target.files, (data) => {
        this.pushSelectPic(data[0].downloadPath)
      })
      e.target.value = ''
    },
    toCamera () {
      this.$refs.camera.dispatchEvent(new MouseEvent('click'))
    },
    addTag () {
      this.$router.push('/meiTu/publishDynamic/selectTag')
    },
    getAddress () {
      this.$router.push('/meiTu/publishDynamic/getAddress')
    },
    linkProduct () {
      this.showSearch = true
      this.submitSearch('')
    },
    submitSearch (value) {
      axios.get(this, `/v1/product`, {
        name: value
      }, (data) => {
        this.searchList = data
      })
    },
    clickProductItem (id, name) {
      this.productId = id
      this.productName = name
      this.showSearch = false
    },
    clickImg (index) {
      // 预览图片
      this.$vux.loading.show({
        text: '加载中...',
        position: 'absolute'
      })
      this.$refs.previewer.show(index)
    },
    preImgLoaded () {
      this.$vux.loading.hide()
    },
    press (index) {
      const _self = this
      this.$vux.confirm.show({
        title: '确定删除张图片吗？',
        onCancel () {
        },
        onConfirm () {
          _self.atlas.splice(index, 1)
        }
      })
    },
    ...mapMutations({
      setSelectPic: 'SET_SELECT_PIC',
      pushSelectPic: 'PUSH_SELECT_PIC'
    })
  }
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/css/variable.styl'

.publishDynamic-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: $color-background;
  z-index: 101;

  .weui-grids {
    .weui-grid {
      padding: 0;
      .img-item {
        margin: 5px;
        text-align: center;
        width: calc(100% - 10px);
        height: 90px;
        background-position: center;
        background-size: cover;
      }
    }
  }

  .topic {
    padding: 12px 15px;

    .content {
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      color: #fff;
      font-size: 14px;
      .tag {
        background: $color-border;
        margin-top: 6px;
        margin-right: 12px;
        padding: 0 8px;
        border-radius: 3px;
        &:hover, &:focus {
          background: #bfbfbf;
        }
      }
    }
  }

  .address {
    position: absolute;
    bottom: 56px;
    left: 0;
    right: 0;
    color: #B2B2B2;
    padding 5px 9px;
    background: rgba(175, 243, 180, 0.5)
    font-size: 13px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .bottom {
    display: flex;
    justify-content: flex-start;
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding-left: 12px;
    padding-bottom: 20px;
    height: 36px;
    line-height: 36px;
    background: #f7f7fa;
    border-top: 1px solid $color-border
    font-size: 21px;
    color: #a3a7ad;
    .icon {
      padding: 0 15px;
    }
  }
}
.popup-wrapper {
  background: #fff;
  overflow: hidden;

  .search-list {
    padding: 15px;
    list-style: none;
    line-height: 1.6;

    li {
      border-bottom: 1px solid $color-border
      padding: 5px 0;
    }
    .name {
      font-weight: bold;
    }
    .feature {
      font-size: 13px;
      color: $color-text-dark;
      overflow : hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style>
